<template>
  <el-container v-if="cfg && cfg.cols" v-loading="load" class="table-all">
    <el-main class="table-main">
      <com-btns
        v-if="(cfg.tableFormBtns && cfg.edit) || cfg.showBtns"
        :btns="cfg.tableFormBtns"
        @outdata2="outdata2"
      />
      <div v-if="cfg.edit" v-show="!cfg.hd" style="margin-bottom: 10px; color: #ff0000; font-size: 12px">
        {{ cfg.tips }}
      </div>
      <el-table
        ref="table"
        class="con-el-table"
        size="mini"
        :data="list"
        :fit="cfg.fit"
        highlight-current-row
        stripe
        border
        :row-key="cfg.key"
        :tree-props="cfg.tree"
        :default-expand-all="cfg.expandAll"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column v-if="cfg.check" type="selection" align="center" min-width="50" />
        <el-table-column
          v-if="cfg.autoId"
          type="index"
          width="50"
          label="序号"
          align="center"
          :index="setIndex"
        />
        <table-col
          v-for="(c, i) in cfg.cols"
          :key="c.col + i + c.width"
          :c="c"
          :cfg="cfg"
          :rows="val"
          :page="me"
          :search-list="searchList"
        />
        <el-table-column v-if="cfg.tableBtns" label="操作" :width="btnWidth">
          <com-btns
            slot-scope="scope"
            inline
            class="btnsCell"
            :btns="cfg.tableBtns"
            :item="scope"
            :reload="getData"
            :re-select="$refs.table.setCurrentRow"
            :table="$refs.table"
            :page="me"
            :table-data="val"
          />
        </el-table-column>
      </el-table>
      <template v-if="cfg.addHad">
        <div :style="{ width: cfg.addWidth + 'px' }" class="add_table_col" @click="addOneCol">+添加一条</div>
      </template>
    </el-main>
    <el-footer v-if="cfg.pager" class="table-footer" height="auto">
      <el-pagination
        v-if="hasPage"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        class="el-page"
        :page-sizes="[10, 20, 30, 50, 100]"
        :total="total"
        :page-size.sync="page._anyline_page_rows"
        :current-page.sync="page._anyline_page"
        @size-change="sizeChange"
        @current-change="getData"
      />
    </el-footer>
  </el-container>
  <el-alert v-else-if="!cfg" title="table 控件没有获取到config配置" type="error" :closable="false" />
  <el-alert v-else title="config 没有获取到cols配置" type="error" :closable="false" />
</template>
<script>
const sizeKey = 'pageSize'
const pageKey = 'page'
import {
  Container as elContainer,
  Footer as elFooter,
  Main as elMain,
  Table as elTable,
  TableColumn as elTableColumn,
  Pagination as elPagination,
  Alert as elAlert
} from 'element-ui'
import { comBtns } from 'qh-common/element'
import control from '../../mixins/control'
import tableCol from './col'
export default {
  name: 'ConTable',
  components: {
    elContainer,
    elFooter,
    elMain,
    elTable,
    elPagination,
    elTableColumn,
    elAlert,
    comBtns,
    tableCol
  },
  mixins: [control],
  props: {
    on: {
      type: Object,
      default(val) {
        return val || {}
      }
    },
    searchList: {
      type: Object,
      default(val) {
        return val || {}
      }
    },
    otherSearch: {
      type: Object,
      default(val) {
        return val || {}
      }
    },
    config: Object,
    closeCol: Boolean,
    IDX: Number
  },
  data() {
    let size = sessionStorage.getItem(sizeKey) * 1
    const page = sessionStorage.getItem(pageKey) * 1
    const self = this
    if (!size || isNaN(size)) {
      size = 10
    }
    return {
      // 选中checkde 集合
      multipleSelection: [],
      // 要合并的单元格的rowspan 数据
      rowspanObj: {},
      me: self,
      load: false,
      total: 0,
      btnWidth: 100,
      hasPage: false,
      isEdit: 0,
      page: {
        _anyline_page_rows: size,
        _anyline_page: page
      },
      order: {
        order: '',
        by: ''
      }
    }
  },
  computed: {
    readOnlys() {
      return this.readOnly
    },
    cfg() {
      const { config } = this
      if (!config) {
        return {}
      }
      const cols =
        config.cols &&
        config.cols.filter(r => {
          return !!r.col
        })
      return {
        showBtns: config.showBtns || false,
        test: config.test,
        key: config.key !== false ? config.key || 'ID' : null,
        autoId: config.autoId === false ? config.autoId : true,
        autoAdd: config.edit ? config.autoAdd : false,
        maps: config.maps || {},
        cols,
        tableFormBtns: config.tableFormBtns,
        uploadForTableInForm: config.uploadForTableInForm,
        tableBtns: config.tableBtns,
        addHad: config.addHad !== false,
        addWidth: config.addWidth,
        expandAll: config.expandAll,
        tree: config.tree,
        dao: config.dao || config.dataSource,
        fit: config.fit === true,
        edit: config.edit === true,
        addOneCol: config.addOneCol === true,
        check: config.check === true,
        load: config.load !== false,
        pager: config.pager !== false,
        hd: config.hd || false,
        timeint: config.timeint || false,
        tips: config.tips || '',
        phoneint: config.phoneint || false,
        islength: config.islength // 视图下标
      }
    },
    returnValue() {
      return this.val
    },
    disabled() {
      return this.config.disabled
    },
    list() {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      this.val = this.val || []
      this.isEdit
      const lastRow = JSON.stringify(this.val[this.val.length - 1])
      if (this.cfg.edit && this.cfg.autoAdd) {
        if (lastRow !== '{}') {
          const tmpRow = {
            id: Symbol()
          }

          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.val.push(tmpRow)
        }
      } else {
        if (lastRow === '{}' && this.val.length > 1 && this.cfg.autoAdd) {
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.val.pop()
        }
      }
      this.$nextTick(this.setBtnColWidth)
      return this.val
    }
  },
  created() {
    this.checkMap()
    this.getData()
  },
  methods: {
    outdata2(v) {
      if (v.FILE_URL && v.FILE_NAME) {
        // const self = this
        this.cfg.tableFormBtns.intem
          .dataFormRun({ FILE_URL: v.FILE_URL, FILE_NAME: v.FILE_NAME })
          .then(res => {
            if (this.val.length) {
              const dsa = res.map(v => v.UNIT_PHONE)
              res.map(v => {
                let p = true
                this.val.map(k => {
                  if (v.PHONE === k.PHONE && dsa.includes(k.UNIT_PHONE) && this.cfg.timeint) {
                    p = false
                    return
                  }
                  if (v.PHONE === k.PHONE && dsa.includes(k.UNIT_PHONE) && this.cfg.phoneint) {
                    p = false
                    return
                  }
                })
                if (p) {
                  this.val.push(v)
                }
              })
            } else {
              this.val = res
            }
          })
          .catch(() => {
            this.cfg.tableFormBtns.intem.load = false
          })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 添加一条
    addOneCol(e) {
      const data = [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ]
      let serialCode = ''
      const l = this.val.length
      for (const m in data) {
        if (Number(this.cfg.islength) === Number(m)) {
          if (l < 9) {
            serialCode = `${data[m - 1]}0${l + 1}`
          } else {
            serialCode = `${data[m - 1]}${l + 1}`
          }
        }
      }

      for (const i in this.val) {
        if (this.val[i].bizCode === '') {
          window.$$.msg.error('请填写编号')
          return
        }
      }
      this.val = this.val || []
      if (this.cfg.edit && this.cfg.addOneCol) {
        // this.cfg.tableBtns.LOOK.disabled = false
        const tmpRow = {
          idIndex: Symbol(),
          // DATA_STATUS: 2,
          bizCode: '',
          serialCode: serialCode,
          name: '',
          unit: '',
          minValue: '',
          middleValue: '',
          maxValue: '',
          dataAssociationMannequinList: [],
          dataAssociationSuggestionList: []
        }
        this.val.push(tmpRow)
        this.$emit('addOneCol', this.val)
      }
    },
    getDataList(datas) {
      this.dataList = datas
    },

    setIndex(i) {
      // let count = this.page._anyline_page_rows;
      let num = this.page._anyline_page - 1
      if (num < 0) {
        num = 0
      }
      return i + 1
    },
    /**
     * 兼容旧版的方法
     */
    // setOldCols(cols) {
    //   if (cols) {
    //     return cols.map((r) => {
    //       r.txt = r.txt || r.viewName;
    //       r.col = r.col || r.colName;
    //       return r;
    //     });
    //   }
    //   return cols;
    // },
    /**
     * 兼容旧版的方法
     */
    getRowData(_anyline_page) {
      this.getData(_anyline_page)
    },
    /**
     * 加载完毕
     */
    over() {
      this.load = false
      this.on.over && this.on.over()
    },
    /**
     * 查询数据
     */
    getData(_anyline_page) {
      if (this.cfg.dao) {
        if (this.cfg.load) {
          this.load = true
        }
        // this.on.before && this.on.before();
        if (_anyline_page) {
          this.page._anyline_page = _anyline_page
        }
        const { searchList, otherSearch, page, order } = this
        sessionStorage.setItem(pageKey, page._anyline_page)
        let queryConditions = Object.assign(searchList, otherSearch, page, order)
        if (this.on.beforeDataLoad) {
          queryConditions = this.on.beforeDataLoad(queryConditions)
        }
        // this.setBtnColWidth();
        // debugger;
        this.cfg
          .dao(queryConditions)
          .then(r => {
            this.over()
            if (r.row) {
              this.val = r.row
            } else {
              this.val = r
            }
            // if (this.config.edit) {
            //   this.config.edit = false
            // }
            this.hasPage = !!r.navi
            if (r.navi) {
              this.total = r.navi.totalRow
            }
            this.$nextTick(() => {
              this.setBtnColWidth()
            })
          })
          .catch(err => {
            this.over()
            window.$$.err(err)
          })
      } else if (this.cfg.test) {
        const row = this.cfg.test
        this.val = row
        this.getDataList(this.val)
      } else {
        const rows = []
        this.val = rows
        this.$nextTick(() => {
          this.setBtnColWidth()
        })
      }
    },
    /**
     * 排序处理
     */
    sortChange(e) {
      const { order } = e
      if (order === 'ascending') {
        this.order.sort = 'asc' // 正序
      } else {
        this.order.sort = 'desc' // 倒序
      }
      // this.order.field = prop
      this.getData()
    },
    /**
     * 计算按钮列宽度
     */
    setBtnColWidth() {
      if (this.cfg.tableBtns && this.$refs.table) {
        const btns = this.$refs.table.$el.getElementsByClassName('btnsCell')
        let w = 0
        let tmp
        for (const $el of btns) {
          tmp = 0
          for (const c of $el.children) {
            tmp += 30 + 13 * c.innerText.trim().length + 10
          }
          tmp > w ? (w = tmp) : 0
        }
        w = w || 66
        if (w) {
          // this.btnWidth = w;
          this.$nextTick(() => {
            if (this.$refs['table']) {
              this.$refs['table'].columns[this.$refs['table'].columns.length - 1].width = w + 11
              this.$refs['table'].doLayout()
            }
          })
        }
      }
    },
    /**
     * 每页展示条数修改
     */
    sizeChange() {
      this.page._anyline_page = 1
      sessionStorage.setItem(sizeKey, this.page._anyline_page_rows)
      this.getData()
    },
    /**
     * 检查map传参
     */
    checkMap() {
      if (this.cfg && this.cfg.cols) {
        for (const c of this.cfg.cols.filter(r => {
          return !r.hidden
        })) {
          if (c.dataType && c.dataType.indexOf('m--') === 0) {
            const key = c.dataType.replace('m--', '')
            if (!this.cfg.maps[key]) {
              window.$$.msg.error(`table控件缺少map入参 [ ${key} ]`)
            }
          }
        }
      }
    },
    /**
     * 获取表格控件
     */
    getTable() {
      return this.$refs.table
    }
  }
}
</script>
<style lang="scss" scoped>
.add_table_col {
  height: 30px;
  background: #ffffff;
  border: 1px dashed #dce0e2;
  border-radius: 3px;
  line-height: 30px;
  text-align: center;
  margin-top: 5px;
  color: #13a8a8;
  cursor: pointer;
  font-size: 12px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #13CE66;
}
.el-form .el-form-item .el-form-item__content .right-parent .bottom-parent > * {
  width: 100%;
}
::v-deep .btns .btn {
  padding: 0 5px 0 0;
}
.btns {
  flex-wrap: nowrap;
}
.con-el-table.el-table .el-table__body-wrapper .el-table__body tr td.edit-cell .cell * {
  border: 1px solid #bfbfbf;
  border-radius: 3px;
}
</style>
